﻿using System;
using System.Collections.Generic;
using System.Text;

namespace YinLongTool.Net.Http
{
    public class MsMultiPartFormData
    {
        private List<byte> formData;

        public string Boundary = "---------------------------23281168279961";

        private string fieldName = "Content-Disposition: form-data; name=\"{0}\"";

        private string fileContentType = "Content-Type: {0}";

        private string fileField = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"";

        private System.Text.Encoding encode = System.Text.Encoding.GetEncoding("UTF-8");

        public System.Text.Encoding Encode
        {
            get
            {
                return encode;
            }
            set
            {
                encode = value;
            }
        }

        public MsMultiPartFormData()
        {
            formData = new List<byte>();
        }

        public void AddFormField(string FieldName, string FieldValue)
        {
            string format = fieldName;
            format = string.Format(format, FieldName);
            formData.AddRange(Encode.GetBytes("--" + Boundary + "\r\n"));
            formData.AddRange(Encode.GetBytes(format + "\r\n\r\n"));
            formData.AddRange(Encode.GetBytes(FieldValue + "\r\n"));
        }

        public void AddFile(string FieldName, string FileName, byte[] FileContent, string ContentType)
        {
            string format = fileField;
            string format2 = fileContentType;
            format = string.Format(format, FieldName, FileName);
            format2 = string.Format(format2, ContentType);
            formData.AddRange(Encode.GetBytes("--" + Boundary + "\r\n"));
            formData.AddRange(Encode.GetBytes(format + "\r\n"));
            formData.AddRange(Encode.GetBytes(format2 + "\r\n\r\n"));
            formData.AddRange(FileContent);
            formData.AddRange(Encode.GetBytes("\r\n"));
        }

        public void AddStreamFile(string FieldName, string FileName, byte[] FileContent)
        {
            AddFile(FieldName, FileName, FileContent, "application/octet-stream");
        }

        public void PrepareFormData()
        {
            formData.AddRange(Encode.GetBytes("--" + Boundary + "--\r\n"));
        }

        public void PrepareFormData(System.Text.Encoding encoding)
        {
            formData.AddRange(encoding.GetBytes("--" + Boundary + "--\r\n"));
        }

        public List<byte> GetFormData()
        {
            return formData;
        }
    }
}
